package info.niwota.web.proxy;

import info.niwota.web.Util;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

import jvs.peer.net.PeerSocket;
import jvs.peer.proxy.SocketRedirectThread;

public class ServerSocketThread extends SocketRedirectThread {
	protected String peer;
	protected String realm;

	public ServerSocketThread(String realm, String peer) throws Exception {
		this.socket = Util.createServerSocket();
		this.realm = realm;
		this.peer = peer;
	}
	
	public ServerSocketThread(String realm, String peer, int port) throws Exception {
		this.socket = new ServerSocket(port);
		this.realm = realm;
		this.peer = peer;
	}

	protected ServerSocket getSocket() {
		return socket;
	}

	public int getPort() {
		return socket.getLocalPort();
	}

	protected void handle(final Socket in) throws Exception {
		Socket out = null;
		try {
			out = new PeerSocket(realm, peer);
			
			tunnel(in, out);
		} catch (Exception e) {
			sendError(in, e);

			close(out);
			close(in);
		}
	}

	private void sendError(Socket in, Exception e) throws IOException {
		PrintStream w = new PrintStream(in.getOutputStream());
		try {
			String msg = "Server has encountered an error: "
					+ e
					+ ". Make sure Bluetooth devices are enabled/paired and try again.";

			w.append("HTTP/1.0 200 OK\r\n");
			w.append("Content-Type: text/html; charset=UTF-8\r\n");
			w.append("Content-Length: " + msg.length() + "\r\n");
			w.append("Connection: close\r\n\r\n");
			w.append(msg);
			w.flush();
		} finally {
			w.close();
		}
	}

}
